<template>
  <Select
    :allow-clear="true"
    v-bind="$attrs"
    v-model:value="state"
    :options="selectOptions"
    :mode="props.mode"
    :on-click="fousIn"
    :open="false"
  />
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="props.title"
    width="1000px"
    heigt="600px"
    @ok="handleSubmit"
    @cancel="handleCancel"
    destroyOnClose
  >
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #tableTop></template>
    </BasicTable>
  </BasicModal>
</template>
<script lang="ts" name="JinhuiEditTableModal" setup>
  import { PropType, ref, toRaw, unref, watchEffect } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicTable } from '/@/components/Table';
  import { useJinhuiTable } from '/@/components/Jinhui/hooks/useJinhuiTable';
  import { ColEx } from '/@/components/Form/src/types';
  import { Select } from 'ant-design-vue';
  import { useRuleFormItem } from '/@/hooks/component/useFormItem';
  import { isFunction } from '/@/utils/is';
  const props = defineProps({
    value: [Object, Array, String],
    schemas: {
      type: Array as PropType<any[]>,
      default: null,
    },
    columns: {
      type: Array as PropType<any[]>,
      default: null,
    },
    api: { type: Function as PropType<(arg?: Recordable) => Promise<Recordable>> },
    params: { type: Object },
    title: { type: String, default: '选择列表' },
    pageSize: { type: Number, default: 5 },
    showIndex: { type: Boolean, default: true },
    mode: { type: String, default: '' },
    rowKey: { type: String, default: 'id' },
    labelField: { type: String, default: 'id' },
    valueField: { type: String, default: 'id' },
  });
  const [registerModal, { openModal }] = useModal();
  // 自适应列配置
  const adaptiveColProps: Partial<ColEx> = {
    xs: 24, // <576px
    sm: 12, // ≥576px
    md: 12, // ≥768px
    lg: 8, // ≥992px
    xl: 8, // ≥1200px
    xxl: 8, // ≥1600px
  };
  const [registerTable, , { selectedRows, rowSelection, selectedRowKeys }] = useJinhuiTable({
    api: props.api,
    beforeFetch: beforeFetch,
    rowKey: props.rowKey,
    rowSelection: { type: props.mode == 'multiple' ? 'checkbox' : 'radio' },
    columns: props.columns,
    formConfig: {
      schemas: props.schemas,
      baseColProps: {
        ...adaptiveColProps,
      },
      autoAdvancedCol: 3,
    },
    pagination: {
      pageSize: props.pageSize,
    },
    showIndexColumn: props.showIndex,
    showTableSetting: false,
    canResize: false,
    showActionColumn: false,
  });
  const emitData = ref<any[]>([]);
  type OptionsItem = { label: string; value: string | Array<any>; disabled?: boolean };
  const selectOptions = ref<OptionsItem[]>([]);
  const [state] = useRuleFormItem(props, 'value', 'change', emitData);
  // 发送请求之前调用的方法
  function beforeFetch(params) {
    // 默认以 createTime 降序排序
    return Object.assign(params, props.params);
  }
  if (state.value == '') {
    state.value = [];
  }
  const selectRowsValue = ref<Recordable<any>[]>([]);
  watchEffect(() => {
    defaultClick();
  });
  //默认事件
  function fousIn() {
    selectRowsValue.value = selectedRows.value;
    //跟选中数据同步,防止选中数据与展示数据不一致
    if (state.value) {
      selectedRowKeys.value = state.value;
    } else {
      selectedRowKeys.value = [];
    }
    openModal(true, {});
  }
  //click事件
  async function defaultClick() {
    //跟选中数据同步,防止选中数据与展示数据不一致
    if (state.value && state.value.length > 0) {
      //根据labelField查询valueField
      const api = props.api;
      if (!api || !isFunction(api)) return;
      const label = props.valueField + '__in';
      let params = {};
      params[label] = state.value;
      await api(params).then((res) => {
        if (res.records) {
          res.records.forEach((item) => {
            selectedRows.value.push(new Proxy(item, {}));
            let json = {};
            json.label = item[props.labelField];
            json.value = item[props.valueField];
            selectOptions.value.push(json);
          });
        }
      });
    }
  }

  //数组去重
  function unRepeat(arr) {
    const res = new Map();
    return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
  }
  //取消
  function handleCancel() {
    //selectedRowKeys.value = [];
  }
  //表单提交事件
  async function handleSubmit() {
    let stateValue = [];
    //合并数组，防止展开modal后因分页原因导致选中的selectedRows不全
    selectedRows.value = [...selectedRows.value, ...selectRowsValue.value];
    const selectedNewRows = unRepeat(selectedRows.value);
    //处理options
    selectedNewRows.forEach((item) => {
      let json = {};
      json.label = item[props.labelField];
      json.value = item[props.valueField];
      selectOptions.value.push(json);
    });
    //处理选中的key
    unref(selectedRowKeys).forEach((item) => {
      stateValue.push(item);
    });
    state.value = stateValue;
    openModal(false, {});
  }
</script>
